package com.hlbspringcloud.contentcenter.configuration;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Description: Nacos权重配置类
 * @PROJECT_NAME: spring-cloud-alibaba
 * @CLASS_NAME:
 * @Author: huanglibin
 * @Date: 2020-05-24 22:35
 * @Version: 1.0
 */
@Slf4j
public class NacosWeightedRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {
        //读取配置文件并初始化NacosWeightedRule,留空即可
    }

    @Override
    public Server choose(Object key) {
        try {
            BaseLoadBalancer loadBalancer = (BaseLoadBalancer) this.getLoadBalancer();
//            log.info("lb={}", loadBalancer);

            //想要请求的微服务的名称
            String name = loadBalancer.getName();

            //拿到服务发现的相关api
            NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();

            //nacos client 自动通过基于权重的负载均衡算法,给我们选择一个实例
            Instance instance = namingService.selectOneHealthyInstance(name);

            log.info("选择的实例是:port = {},instance = {}",instance.getPort(),instance);

            return new NacosServer(instance);
        } catch (NacosException e) {
            log.error(e.getMessage());
            return null;
        }
    }
}
